﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace WF_ExportTool.Common
{
    public  class DbHelper
    {
        #region 属性变量
        public string ConntionString
        {
            get; set;
        }
        /// <summary>
        /// 访问数据库构造函数
        /// </summary>
        /// <param name="dbIns"></param>
        public DbHelper()
        {
            this.ConntionString = System.Configuration.ConfigurationManager.ConnectionStrings["strCon"].ToString();
        }
        #endregion

        #region 创建 Connection 和 Command  
        public IDbConnection GetConnection()
        {
            return new SqlConnection(this.ConntionString);
        }
        private IDataAdapter GetAdapater(string Sql, IDbConnection iConn)
        {
            return new SqlDataAdapter(Sql, (SqlConnection)iConn);              
        }
        #endregion

        /// <summary>  
        /// 执行查询语句   
        /// </summary>  
        /// <param name="SqlString">查询语句</param>  
        /// <returns>DataTable </returns>  
        public DataTable ExecuteDataTable(string sqlString)
        {
            using (IDbConnection iConn = this.GetConnection())
            {
                DataSet ds = new DataSet();
                try
                {
                    IDataAdapter iAdapter = this.GetAdapater(sqlString, iConn);
                    iAdapter.Fill(ds);
                }
                catch (System.Exception e)
                {
                    LogHelper.WriteLog("执行查询语句,发生异常,异常信息为", e);                  
                }
                finally
                {
                    if (iConn.State != ConnectionState.Closed)
                    {
                        iConn.Close();
                    }
                }
                return ds.Tables[0];
            }
        }
    }
}
